package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.emtity.Setmeal;
import com.itheima.reggie.emtity.SetmealDish;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

/*


 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;


    //开启事务
    @Transactional
    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        //存入基础数据
        this.save(setmealDto);
        //B. 获取套餐关联的菜品集合，并为集合中的每一个元素赋值套餐ID(setmealId)
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
            setmealDishService.save(setmealDish);
        }
    }


    @Transactional
    @Override
    public void removeWithDish(List<Long> ids) {
        //A. 查询该批次套餐中是否存在售卖中的套餐, 如果存在, 不允许删除
        //select * from setmeal where id in（1,2,3，） and status = 1；
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.in(Setmeal::getId,ids);
        lqw.eq(Setmeal::getStatus,1);
        int count = this.count(lqw);
        if(count > 0){
            throw new CustomException("套餐正在售卖中，不能删除");
        }
        //B. 若不在售卖中,删除套餐数据
        this.removeByIds(ids);

        //C. 删除套餐关联的菜品数据
        //delete from setmeal_dish where id in (1,2,3)
        LambdaQueryWrapper<SetmealDish> lqw2 = new LambdaQueryWrapper<>();
        lqw2.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(lqw2);

    }
}
